<script setup>
import { Icon } from 'vant';
import videojs from 'video.js'; // 引入Video.js的脚本文件
import 'video.js/dist/video-js.css'; // 引入Video.js的样式文件
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter()
const route = useRoute()

const props = ref(JSON.parse(decodeURIComponent(route.query.it)))

const videoPlayerRef = ref(null)
const layerRef = ref(null)

const options = ref({
    width: '100%',
    height: 'auto',
    preload: 'auto',
    playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2],
    muted: true,
    autoplay: false
})

onMounted(() => {
    if (videoPlayerRef.value) {
        try {
            layerRef.value = ref(videojs(videoPlayerRef.value, options.value))
            layerRef.value.value.play()
        } catch (e) {
            console.error(e)
        }
    }
})

onBeforeUnmount(() => {
    if (layerRef.value) {
        layerRef.value.value.dispose()
    }
})

const onClose = () => {
    router.back()
}

const onDown = () => {
    const a = document.createElement('a')
    a.href = props.value.url;
    a.download = props.value.name;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

</script>

<template>
    <div class="root">
        <video ref="videoPlayerRef" class="video-js"
            style="width: 100%; height: auto; min-height: 100vh; min-width: 100vw;" controls preload="auto">
            <source :src="props.url" :type="props.type">
            <p class="vjs-no-js">
                To view this video please enable JavaScript, and consider upgrading to a web browser that
                <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a>
            </p>
        </video>
    </div>

    <div class="close" @click="onClose">
        <Icon name="cross" size="24px" color="#eeeeee99" />
    </div>
    <div class="down" @click="onDown">
        <Icon name="down" size="24px" color="#eeeeee99" />
    </div>
</template>

<style lang="scss" scoped>
.root {
    background: black;
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.close {
    position: fixed;
    top: 16px;
    right: 16px;
    border: #eeeeee99 solid 2px;
    border-radius: 100px;
    padding: 2px;
    z-index: 100;
    // display: none;
}

.down {
    position: fixed;
    top: 60px;
    right: 16px;
    border: #eeeeee99 solid 2px;
    border-radius: 100px;
    padding: 2px;
    z-index: 100;
}
</style>